package com.haohan.cloud.scm.goods.core.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.cloud.scm.api.constant.ScmCacheNameConstant;
import com.haohan.cloud.scm.api.constant.enums.goods.GoodsStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.opc.YesNoEnum;
import com.haohan.cloud.scm.api.goods.dto.GoodsModelDTO;
import com.haohan.cloud.scm.api.goods.entity.Goods;
import com.haohan.cloud.scm.api.goods.entity.GoodsCategory;
import com.haohan.cloud.scm.api.goods.entity.GoodsModel;
import com.haohan.cloud.scm.api.goods.req.OffGoodsByCateReq;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.goods.core.IScmGoodsService;
import com.haohan.cloud.scm.goods.service.GoodsCategoryService;
import com.haohan.cloud.scm.goods.service.GoodsModelService;
import com.haohan.cloud.scm.goods.service.GoodsService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author cx
 * @date 2019/6/21
 */
@Service
@AllArgsConstructor
public class ScmGoodsServiceImpl implements IScmGoodsService {

    private final GoodsService goodsService;
    private final GoodsModelService goodsModelService;
    private final GoodsCategoryService goodsCategoryService;

//    /**
//     * 获取商品信息
//     *
//     * @return
//     */
//    @Override
//    public List<GoodsInfoDTO> getGoodsInfoDTO() {
//        List<Goods> list = goodsService.list();
//        if (list.isEmpty()) {
//            throw new EmptyDataException();
//        }
//        //查询对应GoodsModel信息和GoodsModelTotal信息
//        List<GoodsInfoDTO> goodsInfoDTOS = this.createGoodsInfoDTO(list);
//        return goodsInfoDTOS;
//    }

//    /**
//     * 查询商品信息
//     *
//     * @param req
//     * @return
//     */
//    @Override
//    public List<GoodsInfoDTO> queryGoodsInfoList(GoodsInfoReq req) {
//        boolean idsFlag = CollUtil.isNotEmpty(req.getGoodsIds());
//        boolean shopIdFlag = StrUtil.isNotEmpty(req.getShopId());
//        if (!idsFlag && !shopIdFlag) {
//            throw new ErrorDataException("查询商品列表时缺参数ids,shopId");
//        }
//        List<Goods> list = goodsService.list(Wrappers.<Goods>query().lambda()
//                .in(idsFlag, Goods::getId, req.getGoodsIds())
//                .eq(shopIdFlag, Goods::getShopId, req.getShopId())
//        );
//        //查询对应GoodsModel信息和GoodsModelTotal信息
//        List<GoodsInfoDTO> goodsInfoDTOS = this.createGoodsInfoDTO(list);
//        return goodsInfoDTOS;
//    }

//    /**
//     * 创建goodsInfoDTO
//     *
//     * @param list
//     * @return
//     */
//    @Override
//    public List<GoodsInfoDTO> createGoodsInfoDTO(List<Goods> list) {
//        List<GoodsInfoDTO> goodsInfoDTOS = new ArrayList<>();
//        for (Goods good : list) {
//            //注入商品信息
//            GoodsPriceRule queryRule = new GoodsPriceRule();
//            queryRule.setGoodsId(good.getId());
//            GoodsPriceRule rule = goodsPriceRuleService.getOne(Wrappers.query(queryRule));
//            GoodsInfoDTO dto = GoodsTrans.goodsInfoDTOTrans(good, rule);
//            //获取商品信息
//            List<String> photos = this.getSliderImage(good.getGoodsSn());
//            //转化为json格式
//            String phoStr = JSONUtil.toJsonStr(photos);
//            dto.setSliderImage(phoStr);
//            //查询商品规格名称列表
//            GoodsModelTotal total = new GoodsModelTotal();
//            total.setGoodsId(good.getId());
//            List<GoodsModelTotal> totals = goodsModelTotalService.list(Wrappers.query(total));
//            dto.setGoodsModelTotals(totals);
//            //查询商品规格信息
//            GoodsModel goodsModel = new GoodsModel();
//            goodsModel.setGoodsId(good.getId());
//            List<GoodsModel> models = goodsModelService.list(Wrappers.query(goodsModel));
//            dto.setModelInfo(models);
//            goodsInfoDTOS.add(dto);
//        }
//        return goodsInfoDTOS;
//    }

//    /**
//     * 查询商品轮播图
//     *
//     * @param goodsSn
//     * @return
//     */
//    @Override
//    public List<String> getSliderImage(String goodsSn) {
//        Goods query = new Goods();
//        query.setGoodsSn(goodsSn);
//        Goods goods = goodsService.getOne(Wrappers.query(query));
//        if (ObjectUtil.isNull(goods)) {
//            return null;
//        }
//        List<String> list = new ArrayList<>();
//        PhotoManageReq req = new PhotoManageReq();
//        if (goods.getPhotoGroupNum() == null) {
//            list.add(goods.getThumbUrl());
//            return list;
//        } else {
//            req.setGroupNum(goods.getPhotoGroupNum());
//        }
//        R r = photoManageFeignService.getPhotoManageList(req, SecurityConstants.FROM_IN);
//        if (!RUtil.isSuccess(r) || r.getData() == null) {
//            throw new EmptyDataException();
//        }
//        List pList = (List) r.getData();
//
//        for (Object obj : pList) {
//            PhotoManage photoManage = BeanUtil.toBean(obj, PhotoManage.class);
//            list.add(photoManage.getPicUrl());
//        }
//        return list;
//    }
//
//    /**
//     * 上传轮播图
//     *
//     * @param req
//     * @return
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Boolean uploadSliderImages(UploadGoodsImageReq req) {
//        String groupId = req.getPhotoGroupNum();
//        if (StrUtil.isNotBlank(groupId)) {
//            if (!req.getDelImages().isEmpty()) {
//                for (String url : req.getDelImages()) {
//                    PhotoManageReq queryReq = new PhotoManageReq();
//                    queryReq.setGroupNum(groupId);
//                    queryReq.setPicUrl(url);
//                    R r = photoManageFeignService.getOneByPhotoManageReq(queryReq, SecurityConstants.FROM_IN);
//                    if (!RUtil.isSuccess(r) || r.getData() == null) {
//                        throw new EmptyDataException("图片不存在");
//                    }
//                    PhotoManage photoManage = BeanUtil.toBean(r.getData(), PhotoManage.class);
//                    R del = photoManageFeignService.removeById(photoManage.getId(), SecurityConstants.FROM_IN);
//                    if (!RUtil.isSuccess(del)) {
//                        throw new ErrorDataException("上传失败");
//                    }
//                }
//            }
//        } else {
//            groupId = scmIncrementUtil.inrcSnByClass(PhotoGroupManage.class, NumberPrefixConstant.PHOTO_GROUP_SN_PR);
//            Goods query = new Goods();
//            query.setGoodsSn(req.getGoodsSn());
//            Goods one = goodsService.getOne(Wrappers.query(query));
//            if (one == null) {
//                throw new EmptyDataException();
//            }
//            Goods upd = new Goods();
//            upd.setId(one.getId());
//            upd.setPhotoGroupNum(groupId);
//            if (!goodsService.updateById(upd)) {
//                throw new ErrorDataException();
//            }
//            PhotoGroupManage manage = new PhotoGroupManage();
//            manage.setGroupNum(groupId);
//            manage.setMerchantId(req.getMerchantId());
//            manage.setGroupName(req.getGoodsName() + "-轮播");
//            manage.setCategoryTag(PhotoTypeEnum.productPhotos.getDesc());
//            R save = photoGroupManageFeignService.save(manage, SecurityConstants.FROM_IN);
//            if (!RUtil.isSuccess(save)) {
//                throw new ErrorDataException();
//            }
//        }
//        if (!req.getUpdImages().isEmpty()) {
//            for (String url : req.getUpdImages()) {
//                PhotoGalleryReq query = new PhotoGalleryReq();
//                query.setPicUrl(url);
//                R r = photoGalleryFeignService.getOneByPhotoGalleryReq(query, SecurityConstants.FROM_IN);
//                if (!RUtil.isSuccess(r) || r.getData() == null) {
//                    throw new EmptyDataException();
//                }
//                PhotoGallery gallery = BeanUtil.toBean(r.getData(), PhotoGallery.class);
//                PhotoManage manage1 = new PhotoManage();
//                manage1.setGroupNum(groupId);
//                manage1.setPhotoGalleryId(gallery.getId());
//                manage1.setPicName(req.getGoodsName());
//                manage1.setPicUrl(url);
//                R save1 = photoManageFeignService.save(manage1, SecurityConstants.FROM_IN);
//                if (!RUtil.isSuccess(save1)) {
//                    throw new ErrorDataException();
//                }
//            }
//        }
//        return true;
//    }

    /**
     * 查询库存预警
     *
     * @param page
     * @param goodsModel
     * @return
     */
    @Override
    public IPage queryStorageWarn(Page page, GoodsModel goodsModel) {
        IPage p = (IPage) page;
        List<GoodsModel> list = goodsModelService.list(Wrappers.query(goodsModel));
        if (list.isEmpty()) {
            throw new EmptyDataException("商品不存在");
        }
        List<GoodsModelDTO> res = new ArrayList<>();
        list.forEach(model -> {
            res.add(goodsModelService.getInfoById(model.getId()));
        });
        if (res.isEmpty()) {
            throw new EmptyDataException("商品库存未到达预警");
        }
        int start = (int) (page.getSize() * (page.getCurrent() - 1));
        int end = (int) (page.getSize() * page.getCurrent());
        if (res.size() >= (page.getSize() * page.getCurrent())) {

            p.setRecords(res.subList(start, end));
        } else {
            int size = (int) page.getSize();
            int surplus = res.size() % size;
            p.setRecords(res.subList(res.size() - surplus - 1, res.size()));
        }
        p.setTotal(res.size());
        return p;
    }

    /**
     * 查询商品规格信息列表
     *
     * @param model
     * @return
     */
    @Override
    public List<GoodsModelDTO> queryGoodsModelDTOList(GoodsModel model) {
        List<GoodsModel> list = goodsModelService.list(Wrappers.query(model));
        if (list.isEmpty()) {
            throw new EmptyDataException();
        }
        List<GoodsModelDTO> res = new ArrayList<>();
        list.forEach(goods -> res.add(goodsModelService.getInfoById(goods.getId())));
        return res;
    }

    /**
     * 修改分类状态
     *
     * @param cate
     * @return
     */
    @Override
    public Boolean changeCateStatus(GoodsCategory cate) {
        GoodsCategory category = goodsCategoryService.getById(cate.getId());
        if (ObjectUtil.isNull(category)) {
            throw new EmptyDataException();
        }
        GoodsCategory upd = new GoodsCategory();
        upd.setId(category.getId());
        upd.setCategoryType(cate.getCategoryType());
        return goodsCategoryService.updateCategoryById(upd);
    }

    /**
     * 按分类下架商品
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = ScmCacheNameConstant.GOODS_CATEGORY_TREE, allEntries = true),
            @CacheEvict(value = ScmCacheNameConstant.WECHAT_BUYER_GOODS_PAGE, allEntries = true),
            @CacheEvict(value = ScmCacheNameConstant.GOODS_INFO_DETAIL, allEntries = true)
    })
    public Boolean offGoodsByCate(OffGoodsByCateReq req) {
        GoodsCategory category = goodsCategoryService.getById(req.getId());
        if (null == category) {
            throw new ErrorDataException("分类有误");
        }
        // 分类及其子类
        Set<String> categoryList = goodsCategoryService.fetchChildren(category.getId());

        Goods updateGoods = new Goods();
        updateGoods.setGoodsStatus(req.getFlag() ? GoodsStatusEnum.sale : GoodsStatusEnum.stock);
        updateGoods.setIsMarketable(req.getFlag() ? 1 : 0);
        goodsService.update(updateGoods, Wrappers.<Goods>query().lambda()
                .in(Goods::getGoodsCategoryId, categoryList)
                // flag: true上架操作时只改下架的
                .eq(Goods::getIsMarketable, req.getFlag() ? 0 : 1)
        );

        categoryList.forEach(categoryId -> {
            // 修改上下架状态
            GoodsCategory update = new GoodsCategory();
            update.setId(categoryId);
            update.setStatus(req.getFlag() ? YesNoEnum.yes : YesNoEnum.no);
            goodsCategoryService.updateCategoryById(update);
        });
        return true;
    }

}
